package com.demiroot.server.pages;

import java.util.Map;

import com.demiroot.server.HTTPResponse;
import com.demiroot.server.HTTPResquest;
import com.demiroot.server.HeaderData;
import com.demiroot.server.Logger;
import com.demiroot.server.Server;
import com.demiroot.server.ServerSession;
import com.demiroot.server.User;
import com.demiroot.server.pages.JavaPageResponse;
import com.demiroot.server.pages.Page;


public class LoggedIn implements Page{
	private String ok = "<html><META http-equiv=\"refresh\" content=\"0;URL=home\">\n" +
	"<body><a href=\"home\">Logged in click here to continue></body></html>";

	private String bad = "<html><META http-equiv=\"refresh\" content=\"5;URL=login\">\n" +
	"<body><a href=\"login\"><font color=\"red\">Login failed click here to continue" +
	"</body></html>";
	

	public HTTPResponse getPage(HTTPResquest request) {
		
		Map<String,String> vars = request.getVars();
		
		if (vars == null) {
			return new JavaPageResponse(bad);
		}
		
		HeaderData head = request.getHeader();
		Server server = request.getServer();
		
		if (vars == null) return new JavaPageResponse(bad);
		String userName = vars.get("user");
		String passwd = vars.get("passwd");
		String sessionID = head.getCookieValue("session");
		ServerSession session = server.getSession(sessionID);
		if (session == null || userName == null || passwd == null 
				|| session == null) {
			return new JavaPageResponse(bad);
		}
		String challenge = (String) session.getVar("challenge");
		session.removeVar("challenge");
		User user = server.getUserManager().getUserByUserID(userName);
		
		Logger.log("login",challenge + " " + user);
		
		if (challenge == null || user == null || !user.passwdMatch(passwd, challenge) ) {
			return new JavaPageResponse(bad);
		}
		
		session.setVar("loggedin", true);
		session.setVar("user", userName);
		session.updateExpire();
		
		return new Home().getPage(request);
	}

	public static boolean isThisYou(String file) {
		return file.equalsIgnoreCase("loggedin");
	}
}
